//
//  LeftChouTiViewController.m
//  HandWork
//
//  Created by 王阳阳 on 16/1/20.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "LeftChouTiViewController.h"
#import "LeftChouTiTableViewCell.h"
#import "OpinionViewController.h"
#import "CollectViewController.h"
#import "NightTableviewCell.h"
#import "UMSocialSnsPlatformManager.h"
#import "UMSocialAccountManager.h"
@interface LeftChouTiViewController ()<UITableViewDataSource, UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, retain) UITableView *tableview;//tableview
@property (nonatomic, retain) UIImageView *img;//cell上的图片
@property (nonatomic, copy) NSString *imgPath;//图片路径
@property (nonatomic, assign) CGFloat j;//文件个数
@property (nonatomic, retain)LeftChouTiTableViewCell *cell;
@end

@implementation LeftChouTiViewController
- (void)dealloc
{
    [_tableview release];
    [_img release];
    [_imgPath release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
//    self.navigationController.navigationBarHidden = YES;//隐藏
    
    
    
    



#pragma mark - 创建tableview
    
    self.tableview = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    //代理
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    //背景颜色
    self.tableview.backgroundColor = [UIColor whiteColor];
    //Tableview添加到view上
    [self.view addSubview:self.tableview];
    //重用池
    [_tableview registerClass:[LeftChouTiTableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableview registerClass:[NightTableviewCell class] forCellReuseIdentifier:@"nightcell"];
    
    [_tableview release];
    
    
    
    //Tableview头部
    [self createHerder];
    
    //tableview的脚部
    self.tableview.tableFooterView = [[UIView alloc] init];

}

#pragma mark - tableview必须实现的两个方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 6) {
        self.cell = [tableView dequeueReusableCellWithIdentifier:@"nightcell" forIndexPath:indexPath];
       
            _cell.namelabel.text = @"夜间模式";
     
    }else{
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        _cell.namelabel.text = @"教程收藏";
    }
    if (indexPath.row == 1) {
        _cell.namelabel.text = @"清除缓存";
        
        
        //创建管理器对象
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //获取沙河路径
        NSString *catch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        if ([fileManager fileExistsAtPath:catch]) {
            NSArray *files = [fileManager subpathsAtPath:catch];
            //遍历所有文件
            for (NSInteger i = 0; i < files.count; i++) {
                NSString *filePath = [catch stringByAppendingPathComponent:files[i]];
                //获取文件大小
                float k = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
                self.j =  self.j + k;
                
            }
        }
        
        
        
        _cell.detailLabel.text = [NSString stringWithFormat:@"%.2fM",self.j / 1024 / 1024];
        
    }

    if (indexPath.row == 2) {
        _cell.namelabel.text = @"关于我们";
        
    }
    if (indexPath.row == 3) {
        _cell.namelabel.text = @"反馈意见";
    
    }
    if (indexPath.row == 4) {
        _cell.namelabel.text = @"用户须知";
    }
    if (indexPath.row == 5) {
        _cell.namelabel.text = @"其他收藏";
    }
    }
    return _cell;
}
#pragma mark - 在tableview的header上添加View VIew上添加头像
-(void)createHerder
{
    //view
    UIView *viewbg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    viewbg.backgroundColor = [UIColor whiteColor];
    [self.tableview addSubview:viewbg];
    self.tableview.tableHeaderView = viewbg;//View作为tableview的头部
    //头部图片
    UIImageView *bgView = [[UIImageView alloc]initWithFrame:viewbg.frame];
    bgView.image = [UIImage imageNamed:@"yinfao.jpg"];
    [viewbg addSubview:bgView];
    [bgView release];
    //高斯模糊
    UIBlurEffect *b = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
   UIVisualEffectView *bV = [[UIVisualEffectView alloc] initWithEffect:b];
    bV.alpha = 0.8;
    bV.frame = bgView.frame;
    [bgView addSubview:bV];
    [bV release];
    
    
    [viewbg release];
    //头像的相框
    UIView *imgbgview = [[UIView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width / 3 + 25, 50, 80, 80)];
    imgbgview.backgroundColor = [UIColor blackColor];
    imgbgview.layer.cornerRadius = 40;//圆角
    [bgView addSubview:imgbgview];
    [imgbgview release];
    //头像
    self.img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    self.img.layer.cornerRadius = 40;//圆角
    self.img.clipsToBounds = YES;
    self.img.tag = 666;
    self.img.image = [UIImage imageNamed:@"yindao2.jpg"];//头像
    [imgbgview addSubview:self.img];
    [self.img release];
    
    //用户交互
    self.img.userInteractionEnabled = YES;
    
    
    
  
    
    
    
    
    
    //手势
    UITapGestureRecognizer *headTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeImage)];
    headTap.numberOfTapsRequired = 1;//点击一下
    [self.img addGestureRecognizer:headTap];//手势添加到头像上
    [headTap release];
 
    //用户名
    UIButton *denglu = [UIButton buttonWithType:UIButtonTypeCustom];
    denglu.frame =CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 30);
    [denglu setTitle:@"点击这里登陆" forState:UIControlStateNormal];
    [denglu addTarget:self action:@selector(denglu) forControlEvents:UIControlEventTouchUpInside];
    denglu.tag = 777;
    [viewbg addSubview:denglu];
    
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userInfo.plist"];
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:path];
    //如果存在则显示
    if (userDic && ([userDic[@"uName"] length] > 0)) {
        [_img sd_setImageWithURL:[NSURL URLWithString:userDic[@"iconUrl"]]];
        [denglu setTitle:userDic[@"uName"] forState:UIControlStateNormal];
    }

 
   
    
}
- (void)denglu
{
    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];
    if (!isLogin) {
        [self loginAndSetUserInfo];//登录并设置用户信息
    }else{
        //判断是否切换用户
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否切换用户" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self loginAndSetUserInfo];//切换用户
        }];
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:yesAction];
        [alert addAction:noAction];
        [self presentViewController:alert animated:yesAction completion:^{
            
        }];
    }

}

#pragma mark -友盟三方登录加设置用户信息
- (void)loginAndSetUserInfo{
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            //改变头像
            UIImageView *headView = [self.view viewWithTag:666];
            [headView sd_setImageWithURL:[NSURL URLWithString:snsAccount.iconURL]];
            //显示名字
            UIButton *but = [self.view viewWithTag:777];
            [but setTitle:snsAccount.userName forState:UIControlStateNormal];
            //登录状态为YES
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLogin"];
            //存本地
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userInfo.plist"];
            NSDictionary *dic = @{@"uName": snsAccount.userName, @"iconUrl": snsAccount.iconURL};
            [dic writeToFile:path atomically:YES];
        }});
    
}

#pragma mark -
- (void)changeImage
{
    
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc]init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    pickerImage.delegate = self;
    //是否可编辑  裁剪
    pickerImage.allowsEditing = YES;
    //跳转到相册页面
    [self presentViewController:pickerImage animated:YES completion:^{
        
    }];
    [pickerImage release];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // [self dismissViewControllerAnimated:YES completion:nil];
    // 将编辑后的图片保存在image中
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    //当图片不为空时显示图片并保存图片
    if (image != nil) {
        //图片显示在界面上
        self.img.image = image;
        
        //以下是保存文件到沙盒路径下
        //把图片转成NSData类型的数据来保存文件
        NSData *data;
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(image);
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        //保存
        [[NSFileManager defaultManager] createFileAtPath:self.imgPath contents:data attributes:nil];
        NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
        [userdefaults setObject:data forKey:@"img"];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        CollectViewController *collect = [[CollectViewController alloc]init];
        [self.navigationController pushViewController:collect animated:YES];
    }
   
    if (indexPath.row == 1) {
        
       //弹出消息框
        

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"清除缓存成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        //延迟
        [self performSelector:@selector(diss:) withObject:alert afterDelay:3];
        
        NSLog(@"%@",NSHomeDirectory());
        //创建管理器对象
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        //获取沙盒路径
//        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        //清除cache
        self.j = 0;
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                           
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           NSLog(@"files :%lu",(unsigned long)[files count]);
                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                           [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
                       });
       
                                   [self.tableview reloadData];
        
        
    }
    if (indexPath.row == 3) {
        //跳转   意见反馈页面
            OpinionViewController *opinion = [[OpinionViewController alloc]init];
        [self presentViewController:opinion animated:YES completion:^{
            
        }];
      
        

    }


}



-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
    
}
#pragma mark - 消息框动画
- (void)diss:(UIAlertController *)a
{
    [a dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)creatFooter
{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 150)];
    footerView.backgroundColor = [UIColor redColor];
    [self.view addSubview:footerView];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
